// 使用立即执行函数避免全局变量污染
(function() {
  console.log('Panel.js 开始加载');

  // 面板实例
  let panelInstance = null;

  // 确保必要的全局变量存在
  if (typeof chrome === 'undefined') {
    console.error('Chrome API 不可用');
    return;
  }

  // 注入面板HTML
  async function injectPanel() {
    try {
      console.log('开始注入面板');
      if (panelInstance) {
        console.log('面板已存在，移除旧面板');
        panelInstance.remove();
      }

      // 创建面板容器
      const panel = document.createElement('div');
      panel.id = 'lofterCrawlerPanel';
      
      // 添加基本结构
      panel.innerHTML = `
        <div class="drag-handle">Lofter图片爬虫</div>
        <button class="minimize-btn">_</button>
        <div class="panel-content">
          <div class="control-panel">
            <div id="templateStatus" class="template-status"></div>
            <label>
              目标图片数量：
              <input type="number" id="targetImages" value="5000" min="1">
            </label>
            <label>
              目标页数：
              <input type="number" id="targetPages" value="50" min="1">
            </label>
          </div>
          <div class="button-group">
            <button id="startCrawl">开始爬取</button>
            <button id="stopCrawl">结束爬取</button>
            <button id="downloadImages">图片下载</button>
            <button id="stopDownload">结束下载</button>
            <button id="crawlAndDownload">爬取并下载</button>
            <button id="stopCrawlDownload">结束下载</button>
            <button id="viewImages">图片预览</button>
            <button id="exportExcel">导出Excel</button>
            <button id="resetAll" class="full-width">重置数据</button>
            <button id="manageTemplates">管理模板</button>
          </div>
          <div class="status-info">
            <p id="articleStatus">已爬取网页：0 个</p>
            <p id="imageStatus">已爬取图片：0 张</p>
            <p id="currentPage">当前页码：0</p>
          </div>


        </div>
      `;

      // 添加到页面
      document.body.appendChild(panel);
      panelInstance = panel;
      
      // 初始化功能
      initializePanel(panel);
      
      console.log('面板注入完成');
      return panel;
    } catch (error) {
      console.error('注入面板失败:', error);
      return null;
    }
  }

  // 初始化面板功能
  function initializePanel(panel) {
    console.log('初始化面板功能');
    
    // 添加最小化功能
    const minimizeBtn = panel.querySelector('.minimize-btn');
    minimizeBtn.addEventListener('click', () => {
      panel.classList.toggle('minimized');
      minimizeBtn.textContent = panel.classList.contains('minimized') ? '□' : '_';
    });
    
    // 添加拖拽功能
    makeDraggable(panel);
    
    // 初始化按钮
    initializeButtons(panel);
  }

  // 初始化按钮
  function initializeButtons(panel) {
    console.log('初始化按钮');
    
    // 防抖函数
    function debounce(func, wait = 1000) {
      let timeout;
      return function (...args) {
        const button = this;
        button.disabled = true;
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          button.disabled = false;
        }, wait);
        func.apply(this, args);
      };
    }
    
    const buttons = {
      'startCrawl': debounce(() => window.startCrawling?.(false)),
      'stopCrawl': debounce(() => window.stopCrawling?.()),
      'viewImages': debounce(() => window.showImages?.()),
      'downloadImages': debounce(() => window.downloadAllImages?.()),
      'crawlAndDownload': debounce(() => window.startCrawling?.(true)),
      'exportExcel': debounce(() => window.exportToExcelFile?.()),
      'resetAll': debounce(() => window.resetAllData?.()),
      'manageTemplates': () => {
        const templateDialog = panel.querySelector('#templateDialog');
        if (templateDialog) {
          templateDialog.style.display = 'flex';
        }
      }
    };

    Object.entries(buttons).forEach(([id, handler]) => {
      const button = panel.querySelector(`#${id}`);
      if (button) {
        button.addEventListener('click', handler);
      }
    });
  }

  // 添加拖拽功能
  function makeDraggable(panel) {
    const dragHandle = panel.querySelector('.drag-handle');
    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;

    dragHandle.addEventListener('mousedown', dragStart);
    document.addEventListener('mousemove', drag);
    document.addEventListener('mouseup', dragEnd);

    function dragStart(e) {
      initialX = e.clientX - xOffset;
      initialY = e.clientY - yOffset;
      if (e.target === dragHandle) {
        isDragging = true;
      }
    }

    function drag(e) {
      if (isDragging) {
        e.preventDefault();
        currentX = e.clientX - initialX;
        currentY = e.clientY - initialY;
        xOffset = currentX;
        yOffset = currentY;
        setTranslate(currentX, currentY, panel);
      }
    }

    function setTranslate(xPos, yPos, el) {
      el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
    }

    function dragEnd() {
      initialX = currentX;
      initialY = currentY;
      isDragging = false;
    }
  }

  // 切换面板显示
  function togglePanel() {
    console.log('切换面板显示');
    if (document.getElementById('lofterCrawlerPanel')) {
      console.log('移除现有面板');
      panelInstance = null;
      document.getElementById('lofterCrawlerPanel').remove();
    } else {
      console.log('注入新面板');
      injectPanel();
    }
  }

  // 导出到全局作用域
  window.togglePanel = togglePanel;

  console.log('Panel.js 加载完成');
})(); 